package com.kdtech.analyse.news;
import com.kdtech.analyse.AnalyseNews;
import com.kdtech.utils.HtmlCleaner;

import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.kdtech.analyse.JSoupUtils;
import com.kdtech.crawler.CrawlHTML;
import com.kdtech.crawler.at.UrlArgumentTop;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.DoMainUtils;
import com.kdtech.utils.HtmlCleaner;

public class DqdailyNewsAnalyse implements AnalyseNews {

	//http://www.dqdaily.com/ztxw/quxpd/2013-05/10/content_1505627.htm
	private static final String[] regex={
		"http://www.dqdaily.com/.*/[0-9]*-[0-9]*/[0-9]*/content_[0-9]*.htm",
		"http://.*.dqdaily.com/.*/[0-9]{4}-[0-9]{2}-[0-9]{2}/[0-9]*.html"
	};

	
	public boolean isDetailPage(String url) {
		for (int i=0; i < regex.length; i++) {
			if (url.matches(regex[i])) {
				return true;
			}
		}
		return false;
	}

	
	public NewsMeta Update(NewsMeta meta) {
		return null;
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		if (urlMeta.getHtml() == null) {
		}
		String url=urlMeta.getUrl();
		if (!isDetailPage(url)) {
		}
		NewsMeta news=new NewsMeta();

		String htmltxt=urlMeta.getHtml();
		Document doc=Jsoup.parse(htmltxt);

		doc.select(".c_right").remove();
		doc.select(".xgxw").remove();
		doc.select("#formComp").remove();
		String title=null;
		String content=null;
		Long date=null;
		title=doc.select("h1").text();
		if(StringUtils.isBlank(title)){
			title=doc.select("td.wzindex_dqbk").text();
		}
		
		content=HtmlCleaner.getContentHtml(url,doc.select("div.c_left div.overflow p"));
		if(StringUtils.isBlank(content)){
			content=HtmlCleaner.getContentHtml(url,doc.select("div#div_content"));
		}
		
		if(StringUtils.isBlank(content)){
			content=HtmlCleaner.getContentHtml(url,doc.select("td.wzcontent_bkq"));
		}
		
		
		date=JSoupUtils.matchDate(doc, "日期:");
		String author=JSoupUtils.matchAuthor(doc, "来源:");
		news.setAuthor(author);
		news.setUrl(url);
		news.setTitle(title);
		news.setContent(content);
		news.setDate(date);
		return news;
	}

	public static void main(String[] args) {
		String url="http://www.dqdaily.com/shishi/2015-06/30/content_2715447.htm";
		DqdailyNewsAnalyse test=new DqdailyNewsAnalyse();
		url=UrlArgumentTop.FromatUrl(url);
		System.out.println(test.isDetailPage(url));
		UrlMeta meta=CrawlHTML.responseToURL(url);
		NewsMeta parserHtml=test.parserHtml(meta);
		System.out.println(parserHtml);
	}

	
	public boolean isNeedUpdate(){
		return false;
	}
}
